#!/usr/bin/perl

##HACKABOT_HELP##
# When was someone last seen and where? (defaults to all chanels)
# !seen [here | #chan] nick
##HACKABOT_HELP##

use strict;
use DBI;
use Time::localtime;
use XML::Simple;

my $CONFIG = XMLin($ENV{'HACKABOT_CFG'}, 
	ForceArray => ['privatechan'],
	KeyAttr => { privatechan => "+chan" });
my $CMDCFG = $CONFIG->{'cmdconfig'}->{'seen'};
my $DBCFG = $CONFIG->{'cmdconfig'}->{'database'};

my $dbhost = $DBCFG->{'host'};
my $dbname = $DBCFG->{'name'};
my $dbuser = $DBCFG->{'user'};
my $dbpass = $DBCFG->{'pass'};

sub seen {
	my $nick = shift;
	my $asker = shift;
	my $chan = shift;
	my $where = shift;
	my ($dbh, $sth);
	my $row;
	my $ret;

	$dbh = DBI->connect("DBI:mysql:$dbname:$dbhost", $dbuser, $dbpass, { PrintError => 1 });
	if (!$dbh) {
		die "see: Failed to connect to database\n";
	}

	my $restrict = "";
	if (defined $where) {
		$restrict .= " AND chan = ".$dbh->quote($where);
	}
	foreach my $priv (keys %{$CMDCFG->{"privatechan"}}) {
		if ($priv eq $chan) {
			next;
		}
		$restrict .= " AND chan != ".$dbh->quote($priv);
	}
	
	$nick = $dbh->quote($nick);

	# Ignore priv for msg, action, notice so chan IS NULL only for quit
	$sth = $dbh->prepare("SELECT date, text, chan, type FROM log WHERE nick = $nick AND ( ( ( type = 'msg' OR type = 'action' OR type = 'notice' OR type = 'join' OR type = 'part' ) AND chan IS NOT NULL  $restrict ) OR ( type = 'quit' AND chan IS NULL ) ) ORDER BY id DESC LIMIT 1");
	$sth->execute();
	if ($row = $sth->fetchrow_hashref) {
		$row->{'text'} =~ s/^"(.*)"$/$1/;
		if ($row->{'type'} eq "msg" or $row->{'type'} eq "notice") {
			$ret = "$asker: $nick was last seen in $row->{'chan'} saying \"$row->{'text'}\" at $row->{'date'}.\n";
		}
		if ($row->{'type'} eq "action") {
			$ret = "$asker: $nick was last seen in $row->{'chan'} saying \"/me $row->{'text'}\" at $row->{'date'}.\n";
		}
		elsif ($row->{'type'} eq "join") {
			$ret = "$asker: $nick was last seen joining $row->{'chan'} at $row->{'date'}.\n";
		}
		elsif ($row->{'type'} eq "part") {
			$ret = "$asker: $nick was last seen leaving $row->{'chan'} saying \"$row->{'text'}\" at $row->{'date'}.\n";
		}
		elsif ($row->{'type'} eq "quit") {
			$ret = "$asker: $nick was last seen quitting with \"$row->{'text'}\" at $row->{'date'}.\n";
		}
	}
	else {
		$ret = "$asker: Sorry, I haven't seen $nick.\n";
	}
	$sth->finish();

	$dbh->disconnect;

	return $ret;
}

my ($nick, $asker, $chan, $where);
while (<>) {
	if (/^nick\s*(\S*)/) {
		$asker = $1;
	}
	if (/^to\s*(\S*)/) {
		$chan = $1;
	}
	elsif (/^msg\s*here\s*(\S*)/) {
		$nick = $1;
		$where = "here";
	}
	elsif (/^msg\s*(#\S*)\s*(\S*)/) {
		$nick = $2;
		$where = $1;
	}
	elsif (/^msg\s*(\S*)/) {
		$nick = $1;
	}
}

if (defined $nick and defined $asker, and defined $chan) {
	if ($where eq "here") {
		print "send " . seen($nick, $asker, $chan, $chan);
	}
	else {
		print "send " . seen($nick, $asker, $chan, $where);
	}
}
else {
	die "seen: All info not sent :-/\n";
}
